import axios from 'axios'
import { ElMessage } from 'element-plus'
import { ElLoading } from 'element-plus'

import userStore1 from "@/store/store1"
const store1 = userStore1()

interface IResponseData<T> {
    code: number,
    message: string,
    data: T
}

let loading:any
class Http {
    instance: any;
    constructor(config: any) {
        this.instance = axios.create(config);
        // 添加请求拦截器
        this.instance.interceptors.request.use(function (config:any) {
            // 在发送请求之前做些什么
             loading = ElLoading.service({
                lock: true,
                text: 'Loading',
                background: 'rgba(0, 0, 0, 0.7)',
            })

            if (store1.token) { //如果需要传token，在请求头上加上token值
                (config.headers as AxiosRequestHeaders).token = store1.token;
            }
            return config;
        }, function (error:any) {
            // 对请求错误做些什么
            loading.close()
            return Promise.reject(error);
        });
        // 添加响应拦截器
        this.instance.interceptors.response.use(function (response:any) {
            // 对响应数据做点什么
            loading.close()
         
            const {code,message,data} = response.data
            if(code == undefined){
              return  response.data;
            }
            if(code === 0){
                return data
            } else if(code != 0 ){
                ElMessage.error(message)
                return  Promise.reject(message)
            }           

            return response;
        }, function (error:any) {
            // 对响应错误做点什么
            loading.close()
            ElMessage.error(error)
            return Promise.reject(error);
        });
    }


    get<T>(url: string, params?: object, data = {}): Promise<IResponseData<T>> {
        return this.instance.get(url, { params, ...data });
    }

    post<T>(url: string, params?: object, data = {}): Promise<IResponseData<T>> {
        return this.instance.post(url, params, data);
    }

    put<T>(url: string, params?: object, data = {}): Promise<IResponseData<T>> {
        return this.instance.put(url, params, data);
    }

    delete<T>(url: string, params?: object, data = {}): Promise<IResponseData<T>> {
        return this.instance.delete(url, { params, ...data });
    }

}
const config = {
    baseURL: '',
    timeout: 30 * 1000,
    withCredentials: true,
}

export default new Http(config);
